﻿using Microsoft.AspNetCore.Mvc.RazorPages;
using Newtonsoft.Json;
using System;
using System.Data;
using System.Net.Http;
using System.Security.Policy;
using System.Text;
using System.Web;
using System.Xml.Linq;
using WebApplication1.Interfaces;
using static System.Runtime.InteropServices.JavaScript.JSType;
//using Newtonsoft.Json.Linq;

namespace WebApplication1.Services
{

    public class LegacyService : ILegacyService
    {
        private readonly HttpClient _httpClient;

        public LegacyService(HttpClient httpClient)
        {
            _httpClient = httpClient;
        }

        public async Task<DataSet> CallLegacyMethodAsync(string str_sql)
        {
            //var content = new StringContent(input, Encoding.UTF8, "application/json");
            //var response = await _httpClient.PostAsync("http://localhost:8080/", content);


            // 方式1：直接拼接
            //var response = await _httpClient.GetAsync($"api/users?name={Uri.EscapeDataString(name)}&page={page}&pageSize={pageSize}");

            // 方式2：使用 UriBuilder（推荐）
            var builder = new UriBuilder("http://localhost:8080/");
            var query = HttpUtility.ParseQueryString(builder.Query);
            query["str_sql"] = str_sql;
            //query["page"] = "23";
            //query["pageSize"] = "232";
            builder.Query = query.ToString();

            var response = await _httpClient.GetAsync(builder.ToString());




            // 自动检查状态码，失败时抛出异常
            /* 类似
             if (response.IsSuccessStatusCode)
            {
                // 处理成功响应
                var data = JsonSerializer.Deserialize<MyData>(content);
                return data;
            }
            else
            {
                // 处理错误
                throw new Exception($"API调用失败: {response.StatusCode}");
            }
             */
            response.EnsureSuccessStatusCode();

            //return await response.Content.ReadAsStringAsync();

            string responseBody = await response.Content.ReadAsStringAsync();

            //System.Text.Json虽然效率高，但其不支持 DataSet 的直接序列化/反序列化
            //继续使用 Newtonsoft.Json（推荐）
            return JsonConvert.DeserializeObject<DataSet>(responseBody);


        }



        public async Task<DataSet> CallService(string srv, string json_dataset)
        {
            /*
            // 自动序列化对象为 JSON
            var user = new User { Name = "John", Email = "john@example.com" };
            var response = await httpClient.PostAsJsonAsync("api/users", user);


            // 需要手动序列化和创建 HttpContent
            var user = new User { Name = "John", Email = "john@example.com" };
            var json = JsonSerializer.Serialize(user);
            var content = new StringContent(json, Encoding.UTF8, "application/json");
            var response = await httpClient.PostAsync("api/users", content);



            var formData = new MultipartFormDataContent();
            formData.Add(new StringContent("John"), "name");
            formData.Add(new StringContent("30"), "age");

            var response = await httpClient.PostAsync("api/upload", formData);


            */
           

            var content = new StringContent(json_dataset, Encoding.UTF8, "application/json");
            //var response = await _httpClient.PostAsync("http://localhost:8080/", content);


            var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost:8080/");
            request.Content = content;







            // 创建 HttpRequestMessage 对象


            // 设置自定义请求头
            request.Headers.Add("X-service", srv);
            request.Headers.Add("X-userid", "admin");
            request.Headers.Add("X-username", Convert.ToBase64String(Encoding.UTF8.GetBytes("管理员" ?? string.Empty)));
            request.Headers.Add("X-fore_ip", "127.0.0.1");
             

            var response = await _httpClient.PostAsync("http://localhost:8080/", content);
            

            // 自动检查状态码，失败时抛出异常
            /* 类似
             if (response.IsSuccessStatusCode)
            {
                // 处理成功响应
                var data = JsonSerializer.Deserialize<MyData>(content);
                return data;
            }
            else
            {
                // 处理错误
                throw new Exception($"API调用失败: {response.StatusCode}");
            }
             */
            response.EnsureSuccessStatusCode();

            //return await response.Content.ReadAsStringAsync();

            string responseBody = await response.Content.ReadAsStringAsync();

            //System.Text.Json虽然效率高，但其不支持 DataSet 的直接序列化/反序列化
            //继续使用 Newtonsoft.Json（推荐）
            return JsonConvert.DeserializeObject<DataSet>(responseBody);


        }


        public async Task<string> CallService_json(string srv, string json_dataset)
        {
            /*
            // 自动序列化对象为 JSON
            var user = new User { Name = "John", Email = "john@example.com" };
            var response = await httpClient.PostAsJsonAsync("api/users", user);


            // 需要手动序列化和创建 HttpContent
            var user = new User { Name = "John", Email = "john@example.com" };
            var json = JsonSerializer.Serialize(user);
            var content = new StringContent(json, Encoding.UTF8, "application/json");
            var response = await httpClient.PostAsync("api/users", content);



            var formData = new MultipartFormDataContent();
            formData.Add(new StringContent("John"), "name");
            formData.Add(new StringContent("30"), "age");

            var response = await httpClient.PostAsync("api/upload", formData);


            */


            var content = new StringContent(json_dataset, Encoding.UTF8, "application/json");
            //var response = await _httpClient.PostAsync("http://localhost:8080/", content);


            // 创建 HttpRequestMessage 对象
            var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost:8080/");
            request.Content = content;

            // 设置自定义请求头[后面从缓存数据库中获取数据；---------------]
            request.Headers.Add("X-service", srv);
            request.Headers.Add("X-userid", "admin");
            request.Headers.Add("X-username", System.Net.WebUtility.HtmlEncode("admin"));
            request.Headers.Add("X-fore_ip", "127.0.0.1");


            var response = await _httpClient.SendAsync(request);
            //var response = await _httpClient.SendAsync(request).ConfigureAwait(false);

            // 自动检查状态码，失败时抛出异常
            /* 类似
             if (response.IsSuccessStatusCode)
            {
                // 处理成功响应
                var data = JsonSerializer.Deserialize<MyData>(content);
                return data;
            }
            else
            {
                // 处理错误
                throw new Exception($"API调用失败: {response.StatusCode}");
            }
             */
            response.EnsureSuccessStatusCode();

            //return await response.Content.ReadAsStringAsync();

            string responseBody = await response.Content.ReadAsStringAsync();

            //System.Text.Json虽然效率高，但其不支持 DataSet 的直接序列化/反序列化
            //继续使用 Newtonsoft.Json（推荐）
            return responseBody;


        }
    }

}
